package com.benyi.byiee.util;

import com.benyi.byiee.model.api.User;

import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

public class RequestContext {
	private static final ThreadLocal<HttpServletRequest > rquest = new ThreadLocal<>();
	private static final ThreadLocal<HttpServletResponse > response = new ThreadLocal<>();
    private static final ThreadLocal<String> requestId = new ThreadLocal<>();
    private static final ThreadLocal<Long> time = new ThreadLocal<>();
    private static final ThreadLocal<User> user = new ThreadLocal<>();
    
    public static void setRequest(HttpServletRequest r) {
    	rquest.set(r);
    	time.set(System.currentTimeMillis());
    } 
    
    public static Long getTime() {
        return time.get();
    }
    
    public static HttpServletRequest getRequest() {
        return rquest.get();
    }
     
    public static void setResponse(HttpServletResponse r) {
    	response.set(r);
    } 
    
    public static HttpServletResponse getResponse() {
        return response.get();
    }
    
    public static void setRequestId(String id) {
        requestId.set(id);
    }
 
    public static String getRequestId() {
        return requestId.get();
    }
    
	public static String getRequestIp() {
		HttpServletRequest req = getRequest();
		if(req==null) {
			return "127.0.0.1";
		}
		String ipAddress = req.getHeader("X-Forwarded-For");
		if (ipAddress != null && !ipAddress.isEmpty() && !"unknown".equalsIgnoreCase(ipAddress)) { 
			ipAddress = ipAddress.split(",")[0].trim();
		} else {
			ipAddress = req.getHeader("X-Real-IP");
			if (ipAddress != null && !ipAddress.isEmpty() && !"unknown".equalsIgnoreCase(ipAddress)) { 
				ipAddress = ipAddress.split(",")[0].trim();
			}else {
				ipAddress = req.getRemoteAddr();  
			} 
		}
		return ipAddress; 
	}
  
    public static void setUser(User u) {
    	user.set(u);
    } 
     
    public static User getUser() {
        return user.get();
    }

    // 清理ThreadLocal
    public static void clear() {
    	rquest.remove();
    	response.remove();
        requestId.remove();
        user.remove();
        time.remove();
    }
}